<?php
namespace Biz;

class TcIM
{
    private $sdkAppId;
    private $identifier;
    private $privateKeyFile;
    private $toolPath;

    function __construct($sdkAppId, $identifier, $privateKeyFile, $toolPath)
    {
        $this->sdkAppId = $sdkAppId;
        $this->identifier = $identifier;
        $this->privateKeyFile = $privateKeyFile;
        $this->toolPath = $toolPath;
    }

    /**
     * 获取Sig，优先从缓存中读取，如果sig失效会自动替换
     * @param  string $privateKey 私钥
     * @param  string $publicKey  公钥
     * @param  int $expire 有效时长（秒）
     * @param  bool $isLatest 为true时不使用缓存
     * @return string             sig
     */
    public function genSig($privateKey, $publicKey, $expire = 60 * 60 * 24 * 180, $isLatest = false)
    {
        $cacheName = 'tx_im_sig_' . $this->identifier;
        vendor('TcIMServerSdk.TLSSig');
        $signature = S($cacheName);
        $errMsg = '';
        $tlssig = new \TLSSigAPI();
        $tlssig->setAppid($this->sdkAppId);
        $tlssig->setPublicKey($publicKey);
        if ($isLatest === true
            || empty($signature)
            || ($tlssig->verifySig($signature['sig'], $this->identifier, $signature['gen_time'], $signature['expire'], $errMsg) === false)) {

            $tlssig->setPrivateKey($privateKey);
            $sig = $tlssig->genSig($this->identifier);
            $signature = [
                'sig' => $sig,
                'gen_time' => time(),
                'expire' => $expire,
            ];
            S($cacheName, $signature, $signature['expire']);
        }
        return $signature['sig'];
    }

    /**
     * 通过调用shell生成签名，注：需要到php.ini开启php的exec方法
     * @param  string  $privateKeyFile 私钥文件路径
     * @param  string  $toolPath       签名工具路径
     * @param  boolean $isLatest       是否强制刷新
     * @return string                  签名
     */
    public function genCmdSig($privateKeyFile, $toolPath, $isLatest = false)
    {
        $cacheName = 'tc_im_sig_' . $this->identifier;
        /* 官方文档上说有效期为180，保险起见，减一天 */
        $expireAfter = 60 * 60 * 24 * 179;
        $signature = S($cacheName);
        if ($isLatest || empty($signature)) {
            vendor('TcIMServerSdk.TimRestApi');
            $api = new \TimRestAPI();
            $api->init($this->sdkAppId, $this->identifier);
            $userSig = $api->generate_user_sig($this->identifier, $expireAfter, $privateKeyFile, $toolPath);
            $signature = [
                'sig' => $userSig,
                'gen_time' => time(),
                'expire' => $expireAfter,
            ];
            S($cacheName, $signature, $expireAfter);
        }
        return $signature['sig'];
    }

    public function createChatroom($username, $roomName)
    {
        vendor('TcIMServerSdk.TimRestApi');
        $api = new \TimRestAPI();
        $userSig = $this->genCmdSig();
        $api->init($this->sdkAppId, $this->identifier);
        $api->set_user_sig($userSig);
        $ret = $api->group_create_group('AVChatRoom', $roomName, $username);
        if ($ret['ErrorCode'] === 0) {
            return $ret['GroupId'];
        } else {
            $errMsg = $ret['ErrorInfo'];
            throw new \Exception($errMsg);
        }
    }

}
